package com.sunlee.app.api.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunlee.app.api.constant.WxConstants;
import com.sunlee.app.api.service.WxMpApiService;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.redis.RedisKeys;
import com.sunlee.common.core.redis.RedisUtils;
import com.sunlee.common.core.utils.RestTemplateUtil;
import com.sunlee.common.core.utils.TimeUtils;
import com.sunlee.app.api.entity.vo.WeChatMiniAuthorizeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.wxbase.wxtoken.JwTokenAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author sunjulei
 * @date 2022/6/29
 */
@Service
@Slf4j
public class WxMpApiServiceImpl implements WxMpApiService {

    @Value("${xjppt.wx.mp.appId}")
    private String appId;
    @Value("${xjppt.wx.mp.appSecret}")
    private String appSecret;

    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private RestTemplateUtil restTemplateUtil;


    @Override
    public String getWxMpAccessToken() {

        String accessToken = redisUtils.get(RedisKeys.getWxMpAccesstoken());

        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }

        try {
            accessToken = JwTokenAPI.getAccessToken(appId, appSecret);
            redisUtils.set(RedisKeys.getWxMpAccesstoken(), accessToken, TimeUtils.HOUR_1);
        } catch (WexinReqException e) {
            log.error("获取微信小程序accessToken异常", e);
        }

        return accessToken;
    }

    @Override
    public WeChatMiniAuthorizeVo wxMpLoginByCode(String code) {

        String url = CharSequenceUtil.format(WxConstants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, appSecret, code);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new BusinessException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                throw new BusinessException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
       return  JSON.parseObject(data.toJSONString(), WeChatMiniAuthorizeVo.class);
    }
}
